package com.lzx.iteam;

import android.app.Dialog;
import android.content.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.*;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;

import android.util.Log;
import android.view.*;
import android.widget.*;
import android.widget.TabHost.TabSpec;
import cn.jpush.android.api.JPushInterface;
import com.lzx.iteam.bean.AppMessage;
import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.contactssearch.conversion.NameConvertService;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.task.UpLoadContactsTask;
import com.lzx.iteam.util.*;
//import com.qihoo.appstore.updatelib.UpdateManager;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Megan on 15/6/23.
 */
public class MainActivity extends FragmentActivity implements View.OnClickListener {

    private final String TAG = "MainActivity";

    public Context mContext;
    public static MainActivity mActivity;
    private PreferenceUtil mPreferenceUtil;
    private AllDialogUtil mDialogUtil;
    private CloudDBOperation mCloudDBOperation;
    private final int MSG_GET_NAMECARD = 1789;
    private final int MSG_GET_IN_APP = 1790;
    private final int MSG_GET_OUT_APP = 1791;
    private final int MSG_GET_USER_INFO = 1794;
    private final int MSG_RONG_TOKEN = 1795;

    public TextView mUnreadNumView;
    public TextView mAllEventReplyUnReadMsg;
    private ImageView mIvHelp;
    private ArrayList<String> mNameCard;
    private String mUserId;
    private String mRongToken;
    public ArrayList<String> eventIds = new ArrayList<String>();

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_GET_IN_APP:
                    if (msg.arg1 == 0) {
                        AppMessage appMessage = (AppMessage) msg.obj;
                        if ("1".equals(appMessage.getOnline())) {//在线

                        } else {//不在线

                        }
                        if (!StringUtil.isEmpty(appMessage.getVersion())) {//有新版本,未测
                            /*if (("ch_baidu").equals(ChannelUtil.getChannel(mContext)) || ("ch_sj91").equals(ChannelUtil.getChannel(mContext))) {
                                BDAutoUpdateSDK.uiUpdateAction(mContext, new UICheckUpdateCallback() {
                                    @Override
                                    public void onCheckComplete() {

                                    }
                                });
                            } else */
                            /*if (("ch_360").equals(ChannelUtil.getChannel(mContext))) {
                                UpdateManager.checkUpdate(mContext, false, true, getPackageName(),
                                      null);
                            } else {
                                checkVersion(appMessage.getVersion(), appMessage.getVersionLog(), appMessage.getDownload());
                            }*/
                            checkVersion(appMessage.getVersion(), appMessage.getVersionLog(), appMessage.getDownload());
                        }
                    } else if (msg.arg1 == 1002 || msg.arg1 == 1003 || msg.arg1 == 1005) {//其他接口也应该加此判断，当前其他接口未加
                        //1002 账号无效    1003 账号过期  1005是账号在其他设备上登录
                        showReLoginDialog((String) msg.obj);
                    } else {
                        Toast.makeText(mContext, (String) msg.obj,
                              Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_GET_NAMECARD:
                    if (msg.arg1 == 0) {
                        mNameCard = (ArrayList<String>) msg.obj;
                        Log.d("mNameCard", " My new  mNameCard  ");
                        RongIM.getInstance().refreshUserInfoCache(new UserInfo(mUserId, mNameCard.get(0), Uri.parse(mNameCard.get(7))));
                    } else {
                        Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_GET_USER_INFO:
                    if (msg.arg1 == 0) {
                        ArrayList<ChatContact> chatContacts = (ArrayList<ChatContact>) msg.obj;
                        ChatContact contact = chatContacts.get(0);
                        Log.d("mNameCard", " Other   info  ");
                        RongIM.getInstance().refreshUserInfoCache(new UserInfo(contact.getUserId(), contact.getUserName(), Uri.parse(contact.getUserImg())));
                    } else {
                        Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_RONG_TOKEN:
                    if (msg.arg1 == 0) {

                        try {
                            JSONObject item = ((JSONObject) msg.obj).getJSONObject(AsynHttpClient.KEY_CC_DATA);
                            mRongToken = item.getString("token");
                            reconnect();

                        } catch (JSONException e) {
                            Log.e("JSONException", e.toString());
                        }

                    } else {
                        Toast.makeText(mContext, (String) msg.obj,
                              Toast.LENGTH_LONG).show();
                    }
                    break;

            }
        }
    };

    /**
     * 其他手机登录提醒
     */
    private void showReLoginDialog(String notice) {

        mDialogUtil.titleMsgBtnStyle("提示", notice, getString(R.string.ok));
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                finish();

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
            }
        });

    }

    private FragmentTabHost mTabHost;
    private LayoutInflater mLayoutInflater;
    /*private Class mFragmentArray[] = {EventsFragment.class, ChatFragment.class, CRMFragment.class,
          ContactsFragment.class, FunctionFragment.class};
    private String mTextArray[] = {"工作", "聊天", "CRM", "团队", "我"};*/

    private Class mFragmentArray[] = {ContactsFragment.class, ChatFragment.class,
          EventsFragment.class, FunctionFragment.class};
    private String mTextArray[] = {"团队", "聊天", "工作", "我"};

    private View getTabItemView(int index) {
        /*int mImageArray[] = {R.drawable.main_event_image_selector,
              R.drawable.main_chat_image_selector, R.drawable.main_crm_image_selector, R.drawable.main_team_image_selector,
              R.drawable.main_aboutme_image_selector};*/
        int mImageArray[] = {R.drawable.main_team_image_selector,
              R.drawable.main_chat_image_selector, R.drawable.main_event_image_selector,
              R.drawable.main_aboutme_image_selector};

        View view = mLayoutInflater.inflate(R.layout.tab_item_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextArray[index]);
        switch (index) {
            case 2:
                mAllEventReplyUnReadMsg = (TextView) view.findViewById(R.id.all_event_unread_msg);
                break;
            case 1:
                mUnreadNumView = (TextView) view.findViewById(R.id.all_message_unread_msg);
                break;

            default:
                break;
        }

        return view;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mActivity = this;
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        mDialogUtil = AllDialogUtil.getInstance(this);
        mCloudDBOperation = new CloudDBOperation(this);
        JPushInterface.stopPush(getApplicationContext());
        //第一次启动显示欢迎页面
        boolean isFirstStart = mPreferenceUtil.getBoolean(PreferenceUtil.IS_FIRST_START, true);
        if (isFirstStart) {
            startActivity(new Intent(this, GuideActivity.class));
            finish();
            return;
        }

        setContentView(R.layout.main_new);
        LocalLogin localLogin = LocalLogin.getInstance();
        if (!localLogin.isLogedin()) {
            localLogin.login(this);
            if (!localLogin.isLogedin()) {
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                return;
            }
            Log.d(TAG, "login === false");
        }
        mUserId = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "");
        // TODO 如果是登录注册忘记密码进来，不重连融云
        if (!"yes".equals(mPreferenceUtil.getString("isLogin", ""))) {
            mRongToken = mPreferenceUtil.getString(AsynHttpClient.KEY_RONG_TOKEN, "");//loginToken
            Log.d(TAG, "isLogin ===  no ");
            // TODO 如果是其他设备登录被顶出，不重连融云
            int other = mPreferenceUtil.getInt("Other_login", 0);
            Log.d(TAG, "isLogin ===  no  other = " + other);
            if (other == 0) {
                reconnect();
            }
        } else {
            Log.d(TAG, "isLogin ===  yes ");
            mPreferenceUtil.save("isLogin", "no");
            rongPrepare();
        }

        mPreferenceUtil.save(PreferenceUtil.TEAM_SID, LocalLogin.getInstance().mSid);
        JPushInterface.resumePush(getApplicationContext());
        String umengChannel = ChannelUtil.getChannel(mContext, "ch_ituandui").trim();
//        AnalyticsConfig.setChannel(umengChannel);
        MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this,"55b1e3e467e58e8669001aee",umengChannel));
        /*if (!"yes".equals(mPreferenceUtil.getString("isLogin", ""))) {
            reqCloudGroupList(this);
        }*/
        uploadNameCard();

        initViews();

        Intent start = new Intent();
        start.setAction("com.lzx.iteam.contactssearch.NameConvertService.START");
        start.setPackage(getPackageName());
        startService(start);

        Intent contact = new Intent();
        contact.setAction("com.lzx.iteam.action.CommonService");
        contact.setPackage(getPackageName());
        startService(contact);

        // TODO 进入和退出走的  app/in 和app/out接口 不走了
//        getInAppMessage();
//        IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//        this.registerReceiver(homeListenerReceiver, homeFilter);

        //        BasicPushNotificationBuilder builder = new Bas、icPushNotificationBuilder(CloudDialerActivity.this);
//        builder.statusBarDrawable = R.drawable.cloud_icon;
//        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;  //设置为自动消失
//        builder.notificationDefaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.DEFAULT_LIGHTS;  // 设置为铃声与震动都要
//        JPushInterface.setPushNotificationBuilder(1, builder);
        new UpLoadContactsTask(this).execute();

        // 360 检查更新
//        UpdateManager.checkUpdate(this);
        Log.d("MainActivity", "--onCreate");
    }

    public RongIM.OnReceiveUnreadCountChangedListener mCountListener = new RongIM.OnReceiveUnreadCountChangedListener() {
        @Override
        public void onMessageIncreased(int count) {

            if (count == 0) {
                mUnreadNumView.setVisibility(View.GONE);
            } else {
                mUnreadNumView.setVisibility(View.VISIBLE);
                if (count < 10) {
                    ViewGroup.LayoutParams linearParams = mUnreadNumView.getLayoutParams();
                    int pd = Constants.dip2px(mContext, 20);
                    linearParams.width = pd;
                    linearParams.height = pd;
                    mUnreadNumView.setLayoutParams(linearParams);
                    mUnreadNumView.setBackgroundResource(R.drawable.unread_1);
                    mUnreadNumView.setGravity(Gravity.CENTER);
                    mUnreadNumView.setText(count + "");
                } else if (count < 100) {
                    ViewGroup.LayoutParams linearParams = mUnreadNumView.getLayoutParams();
                    int widthPx = Constants.dip2px(mContext, 30);
                    int heightPx = Constants.dip2px(mContext, 20);
                    linearParams.width = widthPx;
                    linearParams.height = heightPx;
                    mUnreadNumView.setLayoutParams(linearParams);
                    mUnreadNumView.setBackgroundResource(R.drawable.unread_2);
                    mUnreadNumView.setGravity(Gravity.CENTER);
                    mUnreadNumView.setText(count + "");
                } else if (count >= 100) {
                    ViewGroup.LayoutParams linearParams = mUnreadNumView.getLayoutParams();
                    int widthPx = Constants.dip2px(mContext, 40);
                    int heightPx = Constants.dip2px(mContext, 20);
                    linearParams.width = widthPx;
                    linearParams.height = heightPx;
                    mUnreadNumView.setLayoutParams(linearParams);
                    mUnreadNumView.setBackgroundResource(R.drawable.unread_3);
                    mUnreadNumView.setGravity(Gravity.CENTER);
                    mUnreadNumView.setText("99+");
                }
            }
        }
    };

    private class MyConnectionStatusListener implements RongIMClient.ConnectionStatusListener {

        @Override
        public void onChanged(ConnectionStatus connectionStatus) {

            switch (connectionStatus) {

                case CONNECTED://连接成功。
                    Log.d("My_Rong_Status", "Status == 连接成功 ");
                    break;
                case DISCONNECTED://断开连接。
                    Log.d("My_Rong_Status", "Status == 断开连接 ");
                    break;
                case CONNECTING://连接中。
                    Log.d("ConnectionStatus", "Status == 连接中 ");
                    break;
                case NETWORK_UNAVAILABLE://网络不可用。
                    Log.d("My_Rong_Status", "Status == 网络不可用 ");
                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                    Log.d("My_Rong_Status", "Status == 用户账户在其他设备登录 ");
                    mPreferenceUtil.save("Other_login", 1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showReLoginDialog("账号在其他设备上登陆, 如不是您本人操作请修改账号密码");
                        }
                    });

                    break;
            }
        }
    }


    private void reconnect() {

        RongIM.connect(mRongToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                getRongToken();
                Log.e(TAG, "---onTokenIncorrect--");
            }

            @Override
            public void onSuccess(String s) {
                Log.i(TAG, "---onSuccess--" + s);
                rongPrepare();
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                Log.e(TAG, "---onError--" + e);

            }
        });

    }

    private void rongPrepare() {

        mNameCard = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);

        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            @Override
            public UserInfo getUserInfo(String userId) {

                Log.d("mNameCard", "userId == " + userId);
                if (userId.equals(mUserId)) {
                    if (mNameCard != null && mNameCard.size() > 0) {
                        Log.d("mNameCard", "mNameCard != null");
                        Log.d("mNameCard", "mNameCard = " + mNameCard.toString());
                        return new UserInfo(userId, mNameCard.get(0), Uri.parse(mNameCard.get(7)));//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
                    } else {
                        Log.d("mNameCard", "mNameCard =========== null");
                        return null;
                    }
                } else {
                    getUserInfoMsg(userId);
                    /*if (!StringUtil.isEmpty(userId)){
                        userId = Long.parseLong(userId) + "";
                    }
                    ChatContact user = mCloudDBOperation.findUserMsgById(userId);
                    if (user != null && !StringUtil.isEmpty(user.getUserId())){
                        return new UserInfo(user.getUserId(), user.getUserName(), Uri.parse(user.getUserImg()));
                    }else{
                        return null;
                    }*/
                    return null;

                }

            }

        }, true);
        final Conversation.ConversationType[] conversationTypes = {
              Conversation.ConversationType.PRIVATE,
              Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
              Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE,
              Conversation.ConversationType.DISCUSSION
        };

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                RongIM.getInstance().setOnReceiveUnreadCountChangedListener(mCountListener, conversationTypes);
            }
        }, 500);

        if (RongIM.getInstance() != null && RongIM.getInstance().getRongIMClient() != null) {
            /**
             * 设置连接状态变化的监听器.
             */
            RongIM.getInstance().getRongIMClient().setConnectionStatusListener(new MyConnectionStatusListener());
        }

    }

    public void initViews() {
        mIvHelp = (ImageView) findViewById(R.id.slip_key_create_grou);
        mIvHelp.setOnClickListener(this);
        mLayoutInflater = LayoutInflater.from(this);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        int count = mFragmentArray.length;
        for (int i = 0; i < count; i++) {
            // 给每个Tab按钮设置图标、文字和内容
            TabSpec tabSpec = mTabHost.newTabSpec(mTextArray[i])
                  .setIndicator(getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, mFragmentArray[i], null);
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.slip_key_create_grou:
                mIvHelp.setVisibility(View.GONE);
                mPreferenceUtil.save("create_group_v1", false);
                break;
        }
    }


    /**
     * 获取名片信息
     */
    private void uploadNameCard() {

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        NameCardMessage message = new NameCardMessage(mHandler.obtainMessage(MSG_GET_NAMECARD), this);
        message.mApi = AsynHttpClient.API_USER_MYNAMECARD;
        message.mParams = mList;
        AsynHttpClient.getInstance(mContext).execUserHttp(message);

    }

/*
    public void checkTwoSims(boolean isstart) {
        InputStream is = null;
        BufferedReader br = null;
        MsgCenter mc = MsgCenter.getInstance(mContext);
        try {
            Build bd = new Build();
            String model = bd.MODEL.trim();
            String factory = Build.MANUFACTURER.trim();
            if (isstart) {
                is = getResources().getAssets().open("twosims.txt");
            } else {
                is = openFileInput("twosims.txt");
            }

            br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] strs = line.split(",");
                if (model.equalsIgnoreCase(strs[0]) && factory.equalsIgnoreCase(strs[1])) {
                    mPreferenceUtil.save(PreferenceUtil.IS_TWO_SIM, 1);
                    mPreferenceUtil.save(PreferenceUtil.TWO_SIM_MODEL, strs[0]);
                    mPreferenceUtil.save(PreferenceUtil.TWO_SIM_FACTORY, strs[1]);
                    mPreferenceUtil.save(PreferenceUtil.TWO_SIM_PACKAGE, strs[2]);
                    mPreferenceUtil.save(PreferenceUtil.TWO_SIM_DWONLOAD_URL, strs[3]);
                    mPreferenceUtil.save(PreferenceUtil.TWO_SIM_TYPE, strs[4]);
                    boolean isHaveInstalled = false;
                    PackageManager pm = getPackageManager();
                    try {
                        pm.getApplicationIcon(strs[2]);
                        isHaveInstalled = true;
                    } catch (PackageManager.NameNotFoundException e) {
                        isHaveInstalled = false;
                    }
                    long flag = -1;
                    if (!isHaveInstalled) {
                        flag = mc.typeMsgExist(0, AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN);
                        if (flag == -1) {
                            MsgCenter.MsgDataItem item = new MsgCenter.MsgDataItem();
                            item.cloudId = 0;
                            item.phoneNum = null;
                            item.isReaded = CloudContactsDB.MsgItem.UNREAD;
                            item.dateTime = System.currentTimeMillis();
                            item.execCode = AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN;
                            item.displayText = getString(R.string.localmsg_twosims);
                            item.argList = strs[2] + "," + strs[3];
                            item.msgTypeDrawableId = R.drawable.ic_msg_type;
                            item.nextActionDrawableId = -1;
                            mc.addNewMsg(item);
                        } else {
                            MsgCenter.MsgDataItem item = mc.getMsgItem(flag);
                            item.isReaded = CloudContactsDB.MsgItem.UNREAD;
                            item.msgTypeDrawableId = R.drawable.ic_msg_type;
                            mc.updateMsgReaded(item);
                            //                            if (mFunctionFrag != null)
                            //                                mFunctionFrag.onContentChange();
                        }
                    } else {
                        flag = mc.typeMsgExist(0, AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN);
                        if (flag != -1) {
                            MsgCenter.MsgDataItem item = mc.getMsgItem(flag);
                            item.isReaded = CloudContactsDB.MsgItem.READED;
                            item.msgTypeDrawableId = R.drawable.ic_msg_readed;
                            mc.updateMsgReaded(item);
                            //                            if (mFunctionFrag != null)
                            //                                mFunctionFrag.onContentChange();
                        }
                    }
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
*/

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("MainActivity", "--onResume");

//        if ("yes".equals(mPreferenceUtil.getString("homekey", ""))) {
//            getInAppMessage();
//            IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//            this.registerReceiver(homeListenerReceiver, homeFilter);
//        }
//        mPreferenceUtil.save("homekey", "no");

        MobclickAgent.onResume(this);
        JPushInterface.onResume(this);
        JPushInterface.clearAllNotifications(this);//清除所有通知

    }


    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        JPushInterface.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("MainActivity", "--Destroy");

//        getOutAppMessage();
//        if (homeListenerReceiver != null) {
//            try {
//                this.unregisterReceiver(homeListenerReceiver);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

    }


    /**
     * 监听home键广播
     */
    private BroadcastReceiver homeListenerReceiver = new BroadcastReceiver() {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    // 断掉socket，目前无需断掉，之后只需请求接口通知服务器程序已退到后台即可
                    getOutAppMessage();
                    Log.d("MainActivity", "--HOMEKEY");
                    mPreferenceUtil.save("homekey", "yes");
//                    Toast.makeText(CloudDialerActivity.this,"监听home键的广播",1).show();
                    if (homeListenerReceiver != null) {
                        context.unregisterReceiver(homeListenerReceiver);
                    }

                }
            }
        }
    };

    /**
     * 进入app
     * 1. 关闭推送接口
     * 2. 检查socket是否连接
     * 3. app版本检查
     */
    private void getInAppMessage() {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_CLIENT_TYPE, "1"));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_VERSION, Constants.getVersionName(this)));
        GetAppMessageMsg message = new GetAppMessageMsg(mHandler.obtainMessage(MSG_GET_IN_APP));
        message.mApi = AsynHttpClient.API_APP_IN;
        message.mParams = mList;
        AsynHttpClient.getInstance(mContext).execUserHttp(message);

    }

    /**
     * 进入后台,打开推送接口
     */
    private void getOutAppMessage() {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_GET_OUT_APP));
        message.mApi = AsynHttpClient.API_APP_OUT;
        message.mParams = mList;
        AsynHttpClient.getInstance(mContext).execUserHttp(message);

    }


    /**
     * 版本更新
     */
    public void checkVersion(String versionCode, String versionLog, final String downloadUrl) {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi.isConnected()) {
            try {
                if (!versionCode.equals(Constants.getVersionName(mContext))) {
                    //show dialog
                    mDialogUtil.titleMsgBtnStyle("发现新版本：" + versionCode, versionLog, "现在下载", "以后再说");
                    mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                        @Override
                        public void onConfirmClick(Dialog lDialog) {
                            lDialog.dismiss();
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_Uri = Uri.parse(downloadUrl);
                            intent.setData(content_Uri);
                            startActivity(intent);
                        }

                        @Override
                        public void onCancelClick(Dialog lDialog) {
                            lDialog.dismiss();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
                MobclickAgent.reportError(this, e.toString());
            }
        }
    }


    /**
     * 显示创建团队提示页
     * @param isShow
     */
    public void showHelp(boolean isShow) {
        if (isShow) {
            mIvHelp.setVisibility(View.VISIBLE);
            mPreferenceUtil.save("create_group_v1", false);
        } else {
            mIvHelp.setVisibility(View.GONE);
        }
    }

    public void reqCloudGroupList(Context c) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        GetGroupListMsg getGroup = new GetGroupListMsg(c);
        getGroup.mApi = AsynHttpClient.API_GROUP_GETLIST;
        getGroup.mParams = nvps;
        AsynHttpClient.getInstance(c).execCcHttp(getGroup);
    }

    public void getUserInfoMsg(String uid) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID_OLD, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID, mUserId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_IDS, uid));
        ChatUserInfoMsg msg = new ChatUserInfoMsg(mHandler.obtainMessage(MSG_GET_USER_INFO), this);
        msg.mApi = AsynHttpClient.API_RONG_CHAT_USER_INFO;
        msg.mParams = nvps;
        msg.type = 1;
        AsynHttpClient.getInstance(this).execRongHttp(msg);

    }

    /**
     * 获取融云token
     */
    private void getRongToken() {

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID_OLD, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID, mUserId));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_RONG_TOKEN));
        msg.mApi = AsynHttpClient.API_RONG_CHAT_TOKEN;
        msg.mParams = nvps;
        msg.type = 1;
        AsynHttpClient.getInstance(this).execRongHttp(msg);


    }

}
